<?php
// +----------------------------------------------------------------------
// | Copyright (c) 2020 All rights reserved.
// +----------------------------------------------------------------------
// | User: Simony <1362229026@qq.com>
// | wechat: Shen86579595
// +----------------------------------------------------------------------

namespace app\common\logic;


use GuzzleHttp\Client;

class AppApplePayLogic
{
    private $_http_errors = false;

    private $_err_msg = array(
        '21000' => 'App Store不能读取你提供的JSON对象',
        '21002' => 'receipt-data域的数据有问题',
        '21003' => 'receipt无法通过验证',
        '21004' => '提供的shared secret不匹配你账号中的shared secret',
        '21005' => 'receipt服务器当前不可用',
        '21006' => 'receipt合法，但是订阅已过期。服务器接收到这个状态码时，receipt数据仍然会解码并一起发送',
        '21007' => 'receipt是Sandbox receipt，但却发送至生产系统的验证服务',
        '21008' => 'receipt是生产receipt，但却发送至Sandbox环境的验证服务'
    );


    /**
     * User: Simony
     * Function: 验证苹果支付
     * @param $receipt_data
     * @param bool $isSandbox
     * @return array
     */
    public function validatePay($receipt_data, $isSandbox = false)
    {
        if (strlen($receipt_data) < 20) return ds_arr(ERROR, '参数传递错误');

        //沙箱地址 or 真实运营地址
        $url = $isSandbox ? 'https://sandbox.itunes.apple.com/verifyReceipt' : 'https://buy.itunes.apple.com/verifyReceipt';
        $params = [
            'http_errors' => $this->_http_errors,
            'verify' => false,
            'json' => [
                'receipt-data' => $receipt_data,
            ],
        ];

        try {
            $client = new Client();
            $response = $client->request('POST', $url, $params);
            $res = $response->getBody()->getContents();
            $res = json_decode($res, true);
            return intval($res['status']) === 0 ? ds_arr(SUCCESS, '调用成功', $res) : ds_arr(ERROR, $this->_err_msg[$res['status']], $res);
        } catch (ServerException $e) {
            return ds_arr(ERROR, $e->getMessage());
        } catch (ClientException $e) {
            return ds_arr(ERROR, $e->getMessage());
        }
    }
}
